package cn.walls1717.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * atoMarRef测试
 *
 * @author walls1717
 * @create 2022/12/12 16:47
 **/
@Slf4j
public class AtomicMarkableReferenceDemo {

    public static void main(String[] args) {
        AtomicMarkableReference<Integer> integerAtomicMarkableReference = new AtomicMarkableReference<Integer>(100, false);

        // 用法基本与AtomicStamped一致
        new Thread(()->{
            boolean marked = integerAtomicMarkableReference.isMarked();
            log.info("A 初始marked " + marked);

            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            integerAtomicMarkableReference.compareAndSet(100, 101, marked, !marked);
        }, "A").start();

        new Thread(()->{
            boolean marked = integerAtomicMarkableReference.isMarked();
            log.info("B 初始marked " + marked);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean b = integerAtomicMarkableReference.compareAndSet(100, 2022, marked, !marked);
            log.info("B 是否修改成功 " + b + " " + integerAtomicMarkableReference.isMarked() + integerAtomicMarkableReference.getReference());
        }, "B").start();
    }
}
